local StarMaterial = Material( "gui/silkicons/star" )

COMMVOTE.PlayerPanels = {}
COMMVOTE.MainPanel = nil

function COMMVOTE:OpenPanel()

	if !self.MainPanel then
		
		self.MainPanel = vgui.Create("DFrame")
		self.MainPanel:SetPos( 100, 100 )
		self.MainPanel:SetTitle( "Vote for a commander!" )
		self.MainPanel.OldClose = self.MainPanel.Close
		
		self.MainPanel.Close = function()
			gui.EnableScreenClicker( false )
			COMMVOTE.PlayerPanels = {}
			COMMVOTE.MainPanel:Remove()
			COMMVOTE.MainPanel = nil
		end
		
		
	end
	
	if !IsValid( self.CommIcon ) then
		
		self.CommIcon = vgui.Create("DImage", self.MainPanel )
		self.CommIcon:SetMaterial( StarMaterial )
		self.CommIcon:SizeToContents()
		
	end

	self:UpdateVote()
	
	gui.EnableScreenClicker( true )

end

function COMMVOTE:UpdateVote()

	if !IsValid( self.MainPanel ) then
		return
	end

	local Team = LocalPlayer():Team()

	for k, v in pairs( self.PlayerPanels ) do
		
		if !IsValid( k ) || k:Team() != Team then
			table.remove( self.PlayerPanels, k )		
		end
	
	end

	local CurY = 25
	local HighestVoted = nil
	local HighestCount = 0
	
	for _, v in pairs( player.GetAll() ) do
	
		if v:Team() == Team  then
			
			local panel = self.PlayerPanels[ v ]
			
			if !panel then
				panel = vgui.Create("DButton" , self.MainPanel )
				panel:SetText( v:Name() )
				panel:SetWide( 200 )
				panel.DoClick = function()
					RunConsoleCommand("garc_votecomm", v:EntIndex() )
				end
				
				self.PlayerPanels[ v ] = panel
			end
			
			if !panel.VoteCount then
				
				panel.VoteCount = vgui.Create("DLabel", self.MainPanel )
				panel.VoteCount:SetContentAlignment( 5 )
				
			end
			
			panel:SetPos( 22, CurY )
			
			Msg("Updating comm votes!", v.CommVotes, "\n")
			
			panel.VoteCount:SetText( v.CommVotes or 0 )
			panel.VoteCount:SetSize( 40, panel:GetTall() )
			panel.VoteCount:SetPos( 22 + panel:GetWide() + 5, CurY )
			
			CurY = CurY + panel:GetTall() + 3
			
			if (v.CommVotes or 0) >= HighestCount then
				HighestVoted = v
				HighestCount = v.CommVotes or 0
			end
			
		end
		
	end
	
	if self.PlayerPanels[ HighestVoted ] then
	
		local panel = self.PlayerPanels[ HighestVoted ] 
		
		self.CommIcon:SetPos( 12 - self.CommIcon:GetWide() / 2, panel.y + panel:GetTall() / 2 - self.CommIcon:GetTall() / 2 )		
		
	end
	
	self.MainPanel:SetSize( 266, CurY + 2 )
	

end

hook.Add("CommVotes", "UpdateCount", function()
	timer.Simple( 0, function() COMMVOTE:UpdateVote() end )
end )

hook.Add("ShowSpare2", "ShowVoteCommander", function()
	COMMVOTE:OpenPanel()
end )
